const express = require('express');
const router = express.Router();
const rds = require('../rds.js');
const QRCode = require('qrcode');
const { createCanvas, loadImage } = require('canvas');
const fs = require('fs');
const path = require('path');
const axios = require('axios');

// 获取小程序模块配置
const weappModules = require('../data/weapp-modules.json');
const wework = require('../wework.js');

// ABC孤独症行为量表评定页面路由
router.get('/abc-scale', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例

        // 从数据库获取用户信息
        const query = `
            SELECT uid, real_name
            FROM tutem_mall.eb_user
            WHERE uid = ?
        `;

        const [[userInfo]] = await rds.query(query, [uid]);

        // 获取用户之前的评估记录
        const historyQuery = `
            SELECT id, child_name, child_age, child_gender, total_score, assessment_date, 
                   result_level, result_description
            FROM abc_assessment_records
            WHERE user_id = ?
            ORDER BY assessment_date DESC
            LIMIT 5
        `;

        const [assessmentHistory] = await rds.query(historyQuery, [uid]);

        res.render('scales/abc-scale', {
            title: '孤独症行为量表(ABC)评定',
            userInfo,
            assessmentHistory,
            baseUrl: '/apps' // 添加基础URL前缀
        });
    } catch (error) {
        console.error('ABC量表页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// ABC量表问题获取
router.get('/abc-scale/questions', async (req, res) => {
    try {
        // 获取ABC量表的所有问题
        const query = `
            SELECT id, category, question_text, score_description
            FROM abc_scale_questions
            ORDER BY category, id
        `;

        const [questions] = await rds.query(query);

        // 按类别分组问题
        const categorizedQuestions = {};
        questions.forEach(question => {
            if (!categorizedQuestions[question.category]) {
                categorizedQuestions[question.category] = [];
            }
            categorizedQuestions[question.category].push(question);
        });

        res.json({
            success: true,
            categories: [
                { id: 1, name: "感觉" },
                { id: 2, name: "交往" },
                { id: 3, name: "身体和目标物的使用" },
                { id: 4, name: "语言" },
                { id: 5, name: "自理能力和社会适应" }
            ],
            questions: categorizedQuestions
        });
    } catch (error) {
        console.error('获取ABC量表问题错误:', error);
        res.json({ success: false, message: '获取问题失败' });
    }
});

// 提交ABC量表评估
router.post('/abc-scale/submit', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1;
        const { childName, childAge, childGender, answers } = req.body;

        if (!childName || !childAge || !childGender || !answers) {
            return res.json({ success: false, message: '请填写完整信息' });
        }

        // 计算总分
        let totalScore = 0;
        Object.values(answers).forEach(score => {
            totalScore += parseInt(score);
        });

        // 确定评估结果级别和描述
        let resultLevel, resultDescription;

        if (totalScore <= 31) {
            resultLevel = "正常";
            resultDescription = "您的孩子目前表现为正常范围，无需特别关注。";
        } else if (totalScore <= 52) {
            resultLevel = "疑似";
            resultDescription = "您的孩子疑似有轻微的孤独症特征，建议咨询专业医师进行进一步评估。";
        } else if (totalScore <= 67) {
            resultLevel = "轻度";
            resultDescription = "您的孩子可能存在轻度的孤独症特征，建议咨询专业医师进行进一步评估。";
        } else if (totalScore <= 85) {
            resultLevel = "中度";
            resultDescription = "您的孩子表现出中度孤独症特征，建议尽快寻求专业医疗机构的诊断和干预。";
        } else {
            resultLevel = "重度";
            resultDescription = "您的孩子表现出明显的孤独症特征，请立即寻求专业医疗机构的诊断和干预。";
        }

        // 保存评估记录
        const insertQuery = `
            INSERT INTO abc_assessment_records 
            (user_id, child_name, child_age, child_gender, answers_json, total_score, 
             assessment_date, result_level, result_description)
            VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?)
        `;

        const [result] = await rds.query(insertQuery, [
            uid, 
            childName, 
            childAge, 
            childGender, 
            JSON.stringify(answers), 
            totalScore, 
            resultLevel, 
            resultDescription
        ]);

        res.json({
            success: true,
            assessmentId: result.insertId,
            totalScore,
            resultLevel,
            resultDescription
        });
    } catch (error) {
        console.error('提交ABC量表评估错误:', error);
        res.json({ success: false, message: '提交评估失败' });
    }
});

// 获取ABC量表评估详情
router.get('/abc-scale/result/:id', async (req, res) => {
    try {
        const assessmentId = req.params.id;
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取评估记录
        const query = ` SELECT * FROM abc_assessment_records WHERE id = ? `;
        const [[assessment]] = await rds.query(query, [assessmentId]);
        if (!assessment || ( assessment.user_id != uid && ! isAdmin ) ) {
            return res.status(404).json({ success: false, message: '评估记录不存在或权限不足' });
        }

        // 获取所有问题
        const questionsQuery = ` SELECT id, category, question_text FROM abc_scale_questions ORDER BY category, id `;
        const [questions] = await rds.query(questionsQuery);

        // 解析答案
        const answers = JSON.parse(assessment.answers_json);

        res.render('scales/abc-scale-result', {
            title: 'ABC量表评估结果',
            assessment,
            questions,
            answers,
            baseUrl: '/apps', // 添加基础URL前缀
            categories: [
                { id: 1, name: "感觉" },
                { id: 2, name: "交往" },
                { id: 3, name: "身体和目标物的使用" },
                { id: 4, name: "语言" },
                { id: 5, name: "自理能力和社会适应" }
            ]
        });
    } catch (error) {
        console.error('获取ABC量表评估详情错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 生成ABC量表评估报告
router.get('/abc-scale/report/:id', async (req, res) => {
    try {
        const assessmentId = req.params.id;
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取评估记录
        const query = ` SELECT * FROM abc_assessment_records WHERE id = ?  `;
        const [[assessment]] = await rds.query(query, [assessmentId]);
        if (!assessment || ( assessment.user_id != uid && ! isAdmin ) ) {
            return res.status(404).send('评估结果不存在或无权访问');
        }

        // 获取用户信息
        const userQuery = ` SELECT uid, real_name FROM tutem_mall.eb_user WHERE uid = ?  `;
        const [[userInfo]] = await rds.query(userQuery, [assessment.user_id]);

        // 获取所有问题
        const questionsQuery = `
            SELECT id, category, question_text
            FROM abc_scale_questions
            ORDER BY category, id
        `;

        const [questions] = await rds.query(questionsQuery);

        // 解析答案
        const answers = JSON.parse(assessment.answers_json);

        // 按类别计算分数
        const categoryScores = {};
        questions.forEach(question => {
            if (!categoryScores[question.category]) {
                categoryScores[question.category] = 0;
            }
            if (answers[question.id]) {
                categoryScores[question.category] += parseInt(answers[question.id]);
            }
        });

        // 生成建议
        let suggestions = "";
        if (assessment.result_level === "正常") {
            suggestions = "继续保持良好的亲子互动，定期关注孩子的发展情况。";
        } else if (assessment.result_level === "疑似") {
            suggestions = "建议增加与孩子的互动时间，关注孩子的社交和语言发展、食物与环境，必要时咨询专业医师。";
        } else if (assessment.result_level === "轻度") {
            suggestions = "建议咨询专业医疗机构进行正式评估，同时可以开始营养微生态和早期干预训练，如语言训练、行为训练等。";
        } else if (assessment.result_level === "中度") {
            suggestions = "建议尽快咨询专业医疗机构进行正式评估，同时可以开始营养微生态和早期干预训练，如语言训练、行为训练等。";
        } else {
            suggestions = "请立即寻求专业医疗机构的诊断和干预，制定个性化的治疗方案，包括食物干预、微生态干预、环境干预、行为干预、语言训练、社交技能训练等。";
        }

        res.render('scales/abc-scale-report', {
            title: 'ABC量表评估报告',
            assessment,
            userInfo,
            categoryScores,
            suggestions,
            baseUrl: '/apps', // 添加基础URL前缀
            categories: [
                { id: 1, name: "感觉" },
                { id: 2, name: "交往" },
                { id: 3, name: "身体和目标物的使用" },
                { id: 4, name: "语言" },
                { id: 5, name: "自理能力和社会适应" }
            ]
        });
    } catch (error) {
        console.error('生成ABC量表评估报告错误:', error);
        res.status(500).send('服务器错误');
    }
});

// GSRS胃肠道症状评定量表页面路由
router.get('/gsrs-scale', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例

        // 从数据库获取用户信息
        const query = `
            SELECT uid, real_name
            FROM tutem_mall.eb_user
            WHERE uid = ?
        `;

        const [[userInfo]] = await rds.query(query, [uid]);

        // 获取用户之前的评估记录
        const historyQuery = `
            SELECT id, assessment_date, total_score, result_level, result_description
            FROM gsrs_assessment_records
            WHERE user_id = ?
            ORDER BY assessment_date DESC
            LIMIT 5
        `;

        const [assessmentHistory] = await rds.query(historyQuery, [uid]);

        res.render('scales/gsrs-scale', {
            title: '胃肠道症状评定量表(GSRS)',
            userInfo,
            assessmentHistory,
            baseUrl: '/apps' // 添加基础URL前缀
        });
    } catch (error) {
        console.error('GSRS量表页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// GSRS量表问题获取
router.get('/gsrs-scale/questions', async (req, res) => {
    try {
        // GSRS量表的问题数据
        const questions = [
            { id: 1, category: 1, question_text: "上腹痛" },
            { id: 2, category: 1, question_text: "胸部不适" },
            { id: 3, category: 2, question_text: "反酸" },
            { id: 4, category: 1, question_text: "饥饿痛" },
            { id: 5, category: 2, question_text: "恶心和呕吐" },
            { id: 6, category: 3, question_text: "肠鸣音" },
            { id: 7, category: 3, question_text: "腹胀" },
            { id: 8, category: 3, question_text: "咽部不适" },
            { id: 9, category: 3, question_text: "口气" },
            { id: 10, category: 3, question_text: "小便有异味" },
            { id: 11, category: 4, question_text: "便秘" },
            { id: 12, category: 5, question_text: "腹泻" },
            { id: 13, category: 5, question_text: "大便稀" },
            { id: 14, category: 4, question_text: "大便干结" },
            { id: 15, category: 5, question_text: "有便意需立即排便" },
            { id: 16, category: 5, question_text: "里急后重（排便不尽）" }
        ];

        // 按类别分组问题
        const categorizedQuestions = {};
        questions.forEach(question => {
            if (!categorizedQuestions[question.category]) {
                categorizedQuestions[question.category] = [];
            }
            categorizedQuestions[question.category].push(question);
        });

        res.json({
            success: true,
            categories: [
                { id: 1, name: "腹痛症状" },
                { id: 2, name: "返流症状" },
                { id: 3, name: "消化不良症状" },
                { id: 4, name: "便秘症状" },
                { id: 5, name: "腹泻症状" },
            ],
            questions: categorizedQuestions
        });
    } catch (error) {
        console.error('获取GSRS量表问题错误:', error);
        res.json({ success: false, message: '获取问题失败' });
    }
});

// 提交GSRS量表评估
router.post('/gsrs-scale/submit', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1;
        const { answers } = req.body;

        if (!answers) {
            return res.json({ success: false, message: '请填写完整信息' });
        }

        // 计算总分和各类别分数
        let totalScore = 0;
        const categoryScores = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0};
        const categoryCounts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0};

        // 获取所有问题
        const questions = [
            { id: 1, category: 1, question_text: "上腹痛" },
            { id: 2, category: 1, question_text: "胸部不适" },
            { id: 3, category: 2, question_text: "反酸" },
            { id: 4, category: 1, question_text: "饥饿痛" },
            { id: 5, category: 2, question_text: "恶心和呕吐" },
            { id: 6, category: 3, question_text: "肠鸣音" },
            { id: 7, category: 3, question_text: "腹胀" },
            { id: 8, category: 3, question_text: "咽部不适" },
            { id: 9, category: 3, question_text: "口气" },
            { id: 10, category: 3, question_text: "小便有异味" },
            { id: 11, category: 4, question_text: "便秘" },
            { id: 12, category: 5, question_text: "腹泻" },
            { id: 13, category: 5, question_text: "大便稀" },
            { id: 14, category: 4, question_text: "大便干结" },
            { id: 15, category: 5, question_text: "有便意需立即排便" },
            { id: 16, category: 5, question_text: "里急后重（排便不尽）" }
        ];

        // 计算各类别得分和总分
        questions.forEach(question => {
            if (answers[question.id] !== undefined) {
                const score = parseInt(answers[question.id]);
                totalScore += score;
                categoryScores[question.category] += score;
                categoryCounts[question.category]++;
            }
        });

        // 计算各类别平均分
        for (const category in categoryScores) {
            if (categoryCounts[category] > 0) {
                categoryScores[category] = categoryScores[category] / categoryCounts[category];
            }
        }

        // 计算平均总分
        const avgTotalScore = totalScore / Object.values(answers).length;

        // 确定评估结果级别和描述
        let resultLevel, resultDescription;

        if (avgTotalScore <= 2) {
            resultLevel = "轻微";
            resultDescription = "您的胃肠道症状轻微，属于正常范围内的波动，可以通过调整饮食和生活习惯来改善。";
        } else if (avgTotalScore <= 3) {
            resultLevel = "中度";
            resultDescription = "您的胃肠道症状处于中度水平，建议关注饮食习惯，必要时咨询医生获取专业建议。";
        } else if (avgTotalScore <= 4) {
            resultLevel = "较重";
            resultDescription = "您的胃肠道症状较为严重，建议尽快就医，进行专业检查和治疗。";
        } else {
            resultLevel = "严重";
            resultDescription = "您的胃肠道症状非常严重，请立即就医，接受专业医疗评估和治疗。";
        }

        // 保存评估记录
        const insertQuery = `
            INSERT INTO gsrs_assessment_records 
            (user_id, answers_json, total_score, avg_score, category_scores_json,
             assessment_date, result_level, result_description)
            VALUES (?, ?, ?, ?, ?, NOW(), ?, ?)
        `;

        const [result] = await rds.query(insertQuery, [
            uid, 
            JSON.stringify(answers), 
            totalScore, 
            avgTotalScore.toFixed(2), 
            JSON.stringify(categoryScores), 
            resultLevel, 
            resultDescription
        ]);

        res.json({
            success: true,
            assessmentId: result.insertId,
            totalScore,
            avgScore: avgTotalScore.toFixed(2),
            categoryScores,
            resultLevel,
            resultDescription
        });
    } catch (error) {
        console.error('提交GSRS量表评估错误:', error);
        res.json({ success: false, message: '提交评估失败' });
    }
});

// 获取GSRS量表评估详情
router.get('/gsrs-scale/result/:id', async (req, res) => {

    try {
        const assessmentId = req.params.id;
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取评估记录
        const query = ` SELECT * FROM gsrs_assessment_records WHERE id = ? `;
        const [[assessment]] = await rds.query(query, [assessmentId]);
        if (!assessment || ( assessment.user_id != uid && ! isAdmin ) ) {
            return res.status(404).json({ success: false, message: '评估记录不存在' });
        }

        // 解析答案和类别分数
        const answers = JSON.parse(assessment.answers_json);
        const categoryScores = JSON.parse(assessment.category_scores_json);

        // 获取用户信息
        const userQuery = ` SELECT uid, real_name FROM tutem_mall.eb_user WHERE uid = ?  `;
        const [[userInfo]] = await rds.query(userQuery, [assessment.user_id]);

        res.render('scales/gsrs-scale-result', {
            title: 'GSRS量表评估结果',
            assessment,
            answers,
            categoryScores,
            userInfo,
            baseUrl: '/apps', // 添加基础URL前缀
            categories: [
                { id: 1, name: "腹痛症状" },
                { id: 2, name: "返流症状" },
                { id: 3, name: "消化不良症状" },
                { id: 4, name: "便秘症状" },
                { id: 5, name: "腹泻症状" }
            ],
            questions: [
                { id: 1, category: 1, question_text: "上腹痛" },
                { id: 2, category: 1, question_text: "饥饿痛" },
                { id: 3, category: 2, question_text: "烧心" },
                { id: 4, category: 2, question_text: "反酸" },
                { id: 5, category: 2, question_text: "恶心" },
                { id: 6, category: 2, question_text: "呕吐" },
                { id: 7, category: 3, question_text: "腹鸣" },
                { id: 8, category: 3, question_text: "腹胀" },
                { id: 9, category: 3, question_text: "嗳气" },
                { id: 10, category: 3, question_text: "排气增多" },
                { id: 11, category: 4, question_text: "排便减少" },
                { id: 12, category: 4, question_text: "硬粪" },
                { id: 13, category: 4, question_text: "排便费力" },
                { id: 14, category: 5, question_text: "排便不尽" },
                { id: 15, category: 5, question_text: "排便紧迫感" },
                { id: 16, category: 5, question_text: "稀便" }
            ]
        });
    } catch (error) {
        console.error('获取GSRS量表评估详情错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 生成GSRS量表评估报告
router.get('/gsrs-scale/report/:id', async (req, res) => {
    try {
        const assessmentId = req.params.id;
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取评估记录
        const query = ` SELECT * FROM gsrs_assessment_records WHERE id = ?  `;
        const [[assessment]] = await rds.query(query, [assessmentId]);
        if (!assessment || ( assessment.user_id != uid && ! isAdmin ) ) {
            return res.status(404).send('评估结果不存在或无权访问');
        }

        // 解析类别分数
        const categoryScores = JSON.parse(assessment.category_scores_json);

        // 获取用户信息
        const userQuery = ` SELECT uid, real_name FROM tutem_mall.eb_user WHERE uid = ?  `;
        const [[userInfo]] = await rds.query(userQuery, [assessment.user_id]);

        // 生成建议
        let suggestions = "";
        if (assessment.result_level === "轻微") {
            suggestions = "保持健康的饮食习惯，避免辛辣、油腻食物，规律作息，适当运动，有助于维持胃肠道健康。";
        } else if (assessment.result_level === "中度") {
            suggestions = "建议调整饮食结构，增加膳食纤维摄入，避免刺激性食物，保持规律作息，必要时咨询医生获取专业建议。";
        } else if (assessment.result_level === "较重") {
            suggestions = "建议尽快就医，进行胃肠道相关检查，遵医嘱用药，同时调整饮食和生活习惯，避免加重症状。";
        } else {
            suggestions = "请立即就医，接受专业医疗评估和治疗，严格遵医嘱，调整饮食结构，避免加重病情。";
        }

        // 根据症状类别提供具体建议
        let categoryAdvice = {};

        // 腹痛症状建议
        if (categoryScores[1] > 3) {
            categoryAdvice[1] = "避免过饱进食，少食多餐，睡前3小时内不要进食，睡觉时抬高床头，避免咖啡、酒精、巧克力等刺激性食物。";
        } else if (categoryScores[1] > 2) {
            categoryAdvice[1] = "注意饮食习惯，避免过度进食，减少高脂肪食物摄入，避免睡前进食。";
        } else {
            categoryAdvice[1] = "保持健康饮食习惯，避免过度进食和刺激性食物。";
        }

        // 返流症状建议
        if (categoryScores[2] > 3) {
            categoryAdvice[2] = "避免过饱进食，少食多餐，睡前3小时内不要进食，睡觉时抬高床头，避免咖啡、酒精、巧克力等刺激性食物。";
        } else if (categoryScores[2] > 2) {
            categoryAdvice[2] = "注意饮食习惯，避免过度进食，减少高脂肪食物摄入，避免睡前进食。";
        } else {
            categoryAdvice[2] = "保持健康饮食习惯，避免过度进食和刺激性食物。";
        }

        // 消化不良症状建议
        if (categoryScores[3] > 3) {
            categoryAdvice[3] = "少食多餐，细嚼慢咽，避免高脂肪和难消化食物，减少碳酸饮料摄入，必要时咨询医生。";
        } else if (categoryScores[3] > 2) {
            categoryAdvice[3] = "注意饮食习惯，避免过快进食，减少产气食物摄入，如豆类、洋葱、卷心菜等。";
        } else {
            categoryAdvice[3] = "保持良好的进食习惯，避免过度进食。";
        }

        // 便秘症状建议
        if (categoryScores[4] > 3) {
            categoryAdvice[4] = "增加膳食纤维和水分摄入，保持规律排便习惯，适当运动，必要时在医生指导下使用缓泻剂。";
        } else if (categoryScores[4] > 2) {
            categoryAdvice[4] = "增加蔬果摄入，保证充足水分，养成定时排便习惯，适当运动。";
        } else {
            categoryAdvice[4] = "保持均衡饮食，摄入足够的膳食纤维和水分。";
        }

        // 腹泻症状建议
        if (categoryScores[5] > 3) {
            categoryAdvice[5] = "补充足够的水分和电解质，避免乳制品、咖啡因和高脂食物，可尝试BRAT饮食（香蕉、米饭、苹果酱、吐司），严重时请就医。";
        } else if (categoryScores[5] > 2) {
            categoryAdvice[5] = "注意饮食清淡，避免刺激性食物，保持充分水分摄入，必要时咨询医生。";
        } else {
            categoryAdvice[5] = "保持饮食均衡，避免过度食用刺激性食物。";
        }

        res.render('scales/gsrs-scale-report', {
            title: 'GSRS量表评估报告',
            assessment,
            userInfo,
            categoryScores,
            suggestions,
            categoryAdvice,
            baseUrl: '/apps', // 添加基础URL前缀
            categories: [
                { id: 1, name: "腹痛症状" },
                { id: 2, name: "返流症状" },
                { id: 3, name: "消化不良症状" },
                { id: 4, name: "便秘症状" },
                { id: 5, name: "腹泻症状" }
            ]
        });
    } catch (error) {
        console.error('生成GSRS量表评估报告错误:', error);
        res.status(500).send('服务器错误');
    }
});

/**
 * 量表工具仪表盘页面
 */
router.get('/scales-dashboard', async (req, res) => {
    try {
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取用户信息
        const [[userInfo]] = await rds.query(
            'SELECT * FROM eb_user WHERE uid = ?',
            [uid]
        );

        // 获取用户的评估记录
        let myAssessments = [];

        // 获取ABC量表评估记录
        const [abcRecords] = await rds.query(
            `SELECT * FROM abc_assessment_records 
             WHERE user_id = ? 
             ORDER BY assessment_date DESC`,
            [uid]
        );

        // 获取CABS量表评估记录
        const [cabsRecords] = await rds.query(
            `SELECT * FROM cabs_assessment_records 
             WHERE user_id = ? 
             ORDER BY assessment_date DESC`,
            [uid]
        );

        // 获取GSRS量表评估记录
        const [gsrsRecords] = await rds.query(
            `SELECT * FROM gsrs_assessment_records 
             WHERE user_id = ? 
             ORDER BY assessment_date DESC`,
            [uid]
        );

        // 合并并添加量表类型标识
        abcRecords.forEach(record => {
            record.scale_type = 'abc';
            myAssessments.push(record);
        });

        cabsRecords.forEach(record => {
            record.scale_type = 'cabs';
            myAssessments.push(record);
        });

        gsrsRecords.forEach(record => {
            record.scale_type = 'gsrs';
            myAssessments.push(record);
        });

        // 按评估日期排序
        myAssessments.sort((a, b) => new Date(b.assessment_date) - new Date(a.assessment_date));

        // 获取管理员视图的所有用户评估记录
        let allAssessments = [];

        if (isAdmin) {
            // 获取所有ABC量表评估记录
            const [allAbcRecords] = await rds.query(
                `SELECT ar.*, u.real_name as user_name 
                 FROM abc_assessment_records ar
                 JOIN eb_user u ON ar.user_id = u.uid
                 ORDER BY ar.assessment_date DESC
                 LIMIT 100`
            );

            // 获取所有CABS量表评估记录
            const [allCabsRecords] = await rds.query(
                `SELECT kr.*, u.real_name as user_name 
                 FROM cabs_assessment_records kr
                 JOIN eb_user u ON kr.user_id = u.uid
                 ORDER BY kr.assessment_date DESC
                 LIMIT 100`
            );

            // 获取所有GSRS量表评估记录
            const [allGsrsRecords] = await rds.query(
                `SELECT gr.*, u.real_name as user_name 
                 FROM gsrs_assessment_records gr
                 JOIN eb_user u ON gr.user_id = u.uid
                 ORDER BY gr.assessment_date DESC
                 LIMIT 100`
            );

            // 合并并添加量表类型标识
            allAbcRecords.forEach(record => {
                record.scale_type = 'abc';
                allAssessments.push(record);
            });

            allCabsRecords.forEach(record => {
                record.scale_type = 'cabs';
                allAssessments.push(record);
            });

            allGsrsRecords.forEach(record => {
                record.scale_type = 'gsrs';
                allAssessments.push(record);
            });

            // 按评估日期排序
            allAssessments.sort((a, b) => new Date(b.assessment_date) - new Date(a.assessment_date));
        }

        // 获取各量表的评估记录数量
        const abcCount = abcRecords.length;
        const gsrsCount = gsrsRecords.length;
        const cabsCount = cabsRecords.length;

        res.render('scales/scales-dashboard', {
            userInfo,
            myAssessments,
            allAssessments,
            abcCount,
            gsrsCount,
            cabsCount,
            isAdmin,
            currentYear: new Date().getFullYear()
        });
    } catch (error) {
        console.error('获取量表工具仪表盘数据出错:', error);
        res.status(500).send('服务器错误');
    }
});

// 克氏孤独症行为量表评定页面路由
router.get('/cabs-scale', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例

        // 从数据库获取用户信息
        const query = `
            SELECT uid, real_name
            FROM eb_user
            WHERE uid = ?
        `;
        const [[userInfo]] = await rds.query(query, [uid]);

        // 获取克氏量表问题
        const questions = [
            { id: 1, question_text: '不易与别人混在一起玩', category: 1 },
            { id: 2, question_text: '听而不闻，好象是聋子', category: 1 },
            { id: 3, question_text: '教他学什么，他强烈反抗，如拒绝模仿、说话或做动作', category: 1 },
            { id: 4, question_text: '不顾危险', category: 1 },
            { id: 5, question_text: '不能接受日常习惯的变化', category: 1 },
            { id: 6, question_text: '以手势表达需要', category: 1 },
            { id: 7, question_text: '莫名其妙的笑', category: 1 },
            { id: 8, question_text: '不喜欢被人拥抱', category: 1 },
            { id: 9, question_text: '不停地动，坐不住，活动量大', category: 1 },
            { id: 10, question_text: '不望对方的脸，避免视线的接触', category: 1 },
            { id: 11, question_text: '过度偏爱某些物品', category: 1 },
            { id: 12, question_text: '喜欢旋转的东西', category: 1 },
            { id: 13, question_text: '反复又反复做些怪异的动作或玩耍', category: 1 },
            { id: 14, question_text: '对周围漠不关心', category: 1 }
        ];

        // 获取用户之前的评估记录
        const historyQuery = `
            SELECT id, assessment_date, total_score, result_level, result_description
            FROM cabs_assessment_records
            WHERE user_id = ?
            ORDER BY assessment_date DESC
            LIMIT 5
        `;

        const [assessmentHistory] = await rds.query(historyQuery, [uid]);

        res.render('scales/cabs-scale', {
            userInfo,
            questions,
            assessmentHistory,
            currentYear: new Date().getFullYear()
        });
    } catch (error) {
        console.error('获取克氏孤独症行为量表页面出错:', error);
        res.status(500).send('服务器错误');
    }
});

// 克氏孤独症行为量表提交处理
router.post('/cabs-scale/submit', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1;
        const { child_name, child_age, child_gender, answers } = req.body;

        // 计算总分
        let totalScore = 0;
        for (const [questionId, score] of Object.entries(answers)) {
            totalScore += parseInt(score);
        }

        // 确定结果级别
        let resultLevel = '';
        let resultDescription = '';

        if (totalScore <= 5) {
            resultLevel = '正常';
            resultDescription = '评估结果显示孩子的行为表现在正常范围内，未表现出明显的孤独症特征。';
        } else if (totalScore <= 10) {
            resultLevel = '轻度';
            resultDescription = '评估结果显示孩子可能存在轻微的孤独症特征，建议进一步观察和评估。';
        } else if (totalScore <= 20) {
            resultLevel = '中度';
            resultDescription = '评估结果显示孩子表现出中度孤独症特征，建议咨询专业医师进行进一步评估和干预。';
        } else {
            resultLevel = '重度';
            resultDescription = '评估结果显示孩子表现出明显的孤独症特征，建议尽快寻求专业医疗机构的诊断和干预。';
        }

        // 保存评估结果到数据库
        const insertQuery = `
            INSERT INTO cabs_assessment_records (
                user_id, child_name, child_age, child_gender, 
                answers_json, total_score, result_level, result_description, assessment_date
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        `;

        const [result] = await rds.query(insertQuery, [
            uid, child_name, child_age, child_gender,
            JSON.stringify(answers), totalScore, resultLevel, resultDescription
        ]);

        res.json({
            success: true,
            assessmentId: result.insertId
        });
    } catch (error) {
        console.error('提交克氏孤独症行为量表评估出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误，请稍后重试'
        });
    }
});

// 克氏孤独症行为量表结果页面
router.get('/cabs-scale/result/:id', async (req, res) => {
    try {
        const assessmentId = req.params.id;
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取评估结果
        const assessmentQuery = ` SELECT * FROM cabs_assessment_records WHERE id = ? `;
        const [[assessment]] = await rds.query(assessmentQuery, [assessmentId]);
        if (!assessment || ( assessment.user_id != uid && ! isAdmin ) ) return res.status(404).send('评估结果不存在或无权访问');

        // 获取用户信息
        const userQuery = ` SELECT uid, real_name FROM eb_user WHERE uid = ?  `;
        const [[userInfo]] = await rds.query(userQuery, [assessment.user_id]);

        // 解析答案
        const answers = JSON.parse(assessment.answers_json);

        // 获取克氏量表问题
        const questions = [
            { id: 1, question_text: '不易与别人混在一起玩', category: 1 },
            { id: 2, question_text: '听而不闻，好象是聋子', category: 1 },
            { id: 3, question_text: '教他学什么，他强烈反抗，如拒绝模仿、说话或做动作', category: 1 },
            { id: 4, question_text: '不顾危险', category: 1 },
            { id: 5, question_text: '不能接受日常习惯的变化', category: 1 },
            { id: 6, question_text: '以手势表达需要', category: 1 },
            { id: 7, question_text: '莫名其妙的笑', category: 1 },
            { id: 8, question_text: '不喜欢被人拥抱', category: 1 },
            { id: 9, question_text: '不停地动，坐不住，活动量大', category: 1 },
            { id: 10, question_text: '不望对方的脸，避免视线的接触', category: 1 },
            { id: 11, question_text: '过度偏爱某些物品', category: 1 },
            { id: 12, question_text: '喜欢旋转的东西', category: 1 },
            { id: 13, question_text: '反复又反复做些怪异的动作或玩耍', category: 1 },
            { id: 14, question_text: '对周围漠不关心', category: 1 }
        ];

        res.render('scales/cabs-scale-result', {
            assessment,
            userInfo,
            questions,
            answers,
            baseUrl: '/apps', // 添加基础URL前缀
            currentYear: new Date().getFullYear()
        });
    } catch (error) {
        console.error('获取克氏孤独症行为量表结果页面出错:', error);
        res.status(500).send('服务器错误');
    }
});

// 克氏孤独症行为量表报告页面
router.get('/cabs-scale/report/:id', async (req, res) => {
    try {
        const assessmentId = req.params.id;
        const uid = req.session.totemUID;
        const isAdmin = req.session.trialROLE === 'trial-admin';

        // 获取评估结果
        const assessmentQuery = ` SELECT * FROM cabs_assessment_records WHERE id = ?`;
        const [[assessment]] = await rds.query(assessmentQuery, [assessmentId]);
        if (!assessment || ( assessment.user_id != uid && ! isAdmin ) ) {
            return res.status(404).send('评估结果不存在或无权访问');
        }

        // 获取用户信息
        const userQuery = ` SELECT uid, real_name FROM eb_user WHERE uid = ?  `;
        const [[userInfo]] = await rds.query(userQuery, [assessment.user_id]);

        // 解析答案
        const answers = JSON.parse(assessment.answers_json);

        // 获取克氏量表问题
        const questions = [
            { id: 1, question_text: '不易与别人混在一起玩', category: 1 },
            { id: 2, question_text: '听而不闻，好象是聋子', category: 1 },
            { id: 3, question_text: '教他学什么，他强烈反抗，如拒绝模仿、说话或做动作', category: 1 },
            { id: 4, question_text: '不顾危险', category: 1 },
            { id: 5, question_text: '不能接受日常习惯的变化', category: 1 },
            { id: 6, question_text: '以手势表达需要', category: 1 },
            { id: 7, question_text: '莫名其妙的笑', category: 1 },
            { id: 8, question_text: '不喜欢被人拥抱', category: 1 },
            { id: 9, question_text: '不停地动，坐不住，活动量大', category: 1 },
            { id: 10, question_text: '不望对方的脸，避免视线的接触', category: 1 },
            { id: 11, question_text: '过度偏爱某些物品', category: 1 },
            { id: 12, question_text: '喜欢旋转的东西', category: 1 },
            { id: 13, question_text: '反复又反复做些怪异的动作或玩耍', category: 1 },
            { id: 14, question_text: '对周围漠不关心', category: 1 }
        ];

        // 根据评估结果提供建议
        let suggestions = '';
        if (assessment.result_level === '正常') {
            suggestions = '孩子目前的行为表现在正常范围内，建议继续保持良好的亲子互动和沟通，关注孩子的情感需求和社交发展。定期进行发育监测，确保孩子各方面能力的健康发展。';
        } else if (assessment.result_level === '轻度') {
            suggestions = '建议增加与孩子的互动时间，尝试通过游戏和日常活动促进孩子的社交能力和语言发展。可以考虑咨询儿童发展专家，获取更专业的指导和建议。同时，密切观察孩子的行为变化，定期进行评估。';
        } else if (assessment.result_level === '中度') {
            suggestions = '建议尽快咨询专业的儿童发展医师或儿童精神科医师，进行更全面的评估和诊断。同时，可以开始寻找早期干预服务，如语言治疗、行为干预等。建立规律的生活和学习环境，帮助孩子建立安全感和适应能力。';
        } else {
            suggestions = '请尽快寻求专业医疗机构的诊断和干预。孩子可能需要综合性的干预方案，包括行为干预、语言治疗、职业治疗等。同时，家长也需要学习相关知识和技能，配合专业人员共同帮助孩子。建议加入家长支持团体，分享经验和获取情感支持。';
        }

        res.render('scales/cabs-scale-report', {
            assessment,
            userInfo,
            questions,
            answers,
            suggestions,
            currentYear: new Date().getFullYear()
        });
    } catch (error) {
        console.error('获取克氏孤独症行为量表报告页面出错:', error);
        res.status(500).send('服务器错误');
    }
});

module.exports = router;
